<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-header">
      <view class="search-box">
        <image src="/static/home/search.png" class="search-icon" />
        <input
          type="text"
          v-model="searchText"
          placeholder="搜索商品"
          class="search-input"
          confirm-type="search"
          @confirm="handleSearch"
          focus
        />
        <text 
          v-if="searchText" 
          class="clear-btn" 
          @tap="clearSearch"
        >×</text>
      </view>
      <text 
        class="search-btn" 
        :class="{ active: searchText }"
        @tap="handleSearch"
      >搜索</text>
    </view>

    <!-- 搜索历史 -->
    <view class="history-section" v-if="!searchText && searchHistory.length > 0">
      <view class="section-header">
        <text class="section-title">搜索历史</text>
        <image 
          src="/static/cart/delete.png"
          class="delete-icon" 
          @tap="clearHistory"
        />
      </view>
      <view class="history-tags">
        <text 
          v-for="(item, index) in searchHistory" 
          :key="index"
          class="history-tag"
          @tap="useHistoryItem(item)"
        >{{ item }}</text>
      </view>
    </view>

    <!-- 搜索结果 -->
    <scroll-view
      v-if="searchText"
      class="search-results"
      scroll-y
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 商品列表 -->
      <view class="products-grid">
        <view 
          v-for="product in products" 
          :key="product.id" 
          class="product-card"
          @tap="goToDetail(product.id)"
        >
          <image 
            :src="product.image || '/static/https://fsp-1326500412.cos.ap-chengdu.myqcloud.com/default.png'" 
            mode="aspectFill" 
            class="product-image"
          />
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <view class="product-meta">
              <text class="product-price">¥{{ product.minPrice }}</text>
              <text class="product-sales">已售{{ product.sales || 0 }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view class="loading-more">
        <text v-if="loading">正在加载...</text>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="products.length === 0 && !loading">
        <view class="empty-icon">
          <text class="empty-emoji">🔍</text>
        </view>
        <text class="empty-text">未找到相关商品</text>
        <text class="empty-desc">换个关键词试试吧</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { listProductVoByPageUsingPost } from '@/backend/productController';
import type { API } from '@/backend/typings';

// 搜索相关状态
const searchText = ref('');
const searchHistory = ref<string[]>([]);
const products = ref<API.ProductVO[]>([]);
const loading = ref(false);
const refreshing = ref(false);
const hasMore = ref(true);
const current = ref(1);
const pageSize = ref(10);
const searchKeyword = ref('');

// 获取搜索历史
const loadSearchHistory = () => {
  const history = uni.getStorageSync('searchHistory');
  if (history) {
    searchHistory.value = JSON.parse(history);
  }
};

// 保存搜索历史
const saveSearchHistory = (keyword: string) => {
  if (!keyword.trim()) return;
  let history = searchHistory.value;
  // 删除已存在的相同关键词
  history = history.filter(item => item !== keyword);
  // 将新关键词添加到开头
  history.unshift(keyword);
  // 只保留最近10条
  history = history.slice(0, 10);
  searchHistory.value = history;
  uni.setStorageSync('searchHistory', JSON.stringify(history));
};

// 清空搜索历史
const clearHistory = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空搜索历史吗？',
    success: (res) => {
      if (res.confirm) {
        searchHistory.value = [];
        uni.removeStorageSync('searchHistory');
      }
    }
  });
};

// 使用历史记录项
const useHistoryItem = (keyword: string) => {
  searchText.value = keyword;
  handleSearch();
};

// 清空搜索
const clearSearch = () => {
  searchText.value = '';
  products.value = [];
};

// 接收搜索关键词
onLoad((query) => {
  if (query.keyword) {
    searchKeyword.value = decodeURIComponent(query.keyword);
    searchText.value = searchKeyword.value;
    handleSearch();
  }
});

// 搜索商品
const searchProducts = async (refresh = false) => {
  if (loading.value) return;
  
  if (refresh) {
    current.value = 1;
    products.value = [];
    hasMore.value = true;
  }

  loading.value = true;
  try {
    const res = await listProductVoByPageUsingPost({
      name: searchText.value,
      current: current.value,
      pageSize: pageSize.value,
      sortField: 'createTime',
      sortOrder: 'desc',
      status: 'active'
    });

    if (res.code === 0 && res.data) {
      const newProducts = res.data.records || [];
      if (refresh) {
        products.value = newProducts;
      } else {
        products.value = [...products.value, ...newProducts];
      }
      
      hasMore.value = newProducts.length === pageSize.value;
      if (refresh) {
        saveSearchHistory(searchText.value);
      }
    }
  } catch (error) {
    console.error('搜索商品失败：', error);
    uni.showToast({
      title: '搜索失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 处理搜索
const handleSearch = async () => {
  if (!searchText.value.trim()) return;
  
  searchKeyword.value = searchText.value.trim();
  current.value = 1;
  products.value = [];
  await searchProducts(true);
  
  // 保存搜索历史
  saveSearchHistory(searchKeyword.value);
};

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value) return;
  current.value++;
  searchProducts();
};

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  await searchProducts(true);
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 跳转到商品详情
const goToDetail = (id?: number) => {
  if (!id) return;
  uni.navigateTo({
    url: `/pages/product/detail?id=${id}`
  });
};

onMounted(() => {
  loadSearchHistory();
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #fff;
  padding-top: var(--status-bar-height);
}

.search-header {
  padding: 20rpx 30rpx;
  background: #fff;
  display: flex;
  align-items: center;
  gap: 20rpx;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
}

.search-box {
  flex: 1;
  height: 80rpx;
  background: #f8f8f8;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  transition: all 0.3s ease;
}

.search-box:active,
.search-input:focus {
  transform: scale(1.02);
  box-shadow: 0 4rpx 20rpx rgba(255, 87, 34, 0.1);
}

.search-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 16rpx;
  opacity: 0.6;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 30rpx;
  color: #333;
}

.clear-btn {
  font-size: 40rpx;
  color: #999;
  padding: 0 10rpx;
  transition: all 0.2s ease;
}

.search-btn {
  font-size: 32rpx;
  color: #999;
  padding: 0 20rpx;
  transition: all 0.3s ease;
}

.search-btn.active {
  color: #ff5722;
  font-weight: 500;
  transform: scale(1.05);
}

.history-section {
  background: #fff;
  padding: 30rpx;
  margin-top: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.delete-icon {
  width: 32rpx;
  height: 32rpx;
  padding: 10rpx;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.history-tag {
  padding: 16rpx 32rpx;
  background: #f8f8f8;
  border-radius: 40rpx;
  font-size: 26rpx;
  color: #666;
  transition: all 0.2s ease;
}

.history-tag:active {
  background: #fff2ed;
  color: #ff5722;
  transform: scale(0.95);
}

.search-results {
  padding: 0 20rpx;
}

.search-results::before {
  content: "搜索结果";
  display: block;
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  padding: 30rpx 0 20rpx;
  border-bottom: 2rpx solid #f5f5f5;
  margin-bottom: 20rpx;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
  padding: 0 24rpx;
}

.product-card {
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 6rpx 24rpx rgba(0,0,0,0.06);
  transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  position: relative;
}

.product-card:active {
  transform: translateY(-4rpx);
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.1);
}

.product-image {
  width: 100%;
  height: 360rpx;
  background: #f8f8f8;
  transition: transform 0.3s ease;
}

.product-info {
  padding: 24rpx;
}

.product-name {
  font-size: 30rpx;
  line-height: 1.4;
  min-height: 84rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 16rpx;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 34rpx;
  color: #ff5722;
  font-weight: 700;
}

.product-sales {
  font-size: 24rpx;
  color: #999;
  background: #f8f8f8;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.loading-more {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}

.empty-state {
  padding: 120rpx 30rpx;
  text-align: center;
  animation: fadeIn 0.6s ease;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  background: #fff2ed;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
  animation: float 3s ease-in-out infinite;
}

.empty-emoji {
  font-size: 80rpx;
  line-height: 1;
}

.empty-text {
  font-size: 36rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
  display: block;
}

.empty-desc {
  font-size: 28rpx;
  color: #999;
  display: block;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(40rpx); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-20rpx); }
}
</style> 